package com.constructiveproof.example.auth.strategies

import org.scalatra.ScalatraBase
import org.scalatra.auth.ScentryStrategy
import com.constructiveproof.example.models.User
import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
import org.slf4j.LoggerFactory

/*
* 密码验证策略
*
*
* */
class UserPasswordStrategy(protected val app: ScalatraBase)(implicit request: HttpServletRequest, response: HttpServletResponse)
  extends ScentryStrategy[User] {

  val logger = LoggerFactory.getLogger(getClass)

  //定义策略名
  override def name: String = "UserPassword"

  //获取请求参数
  private def login = app.params.getOrElse("login", "")
  private def password = app.params.getOrElse("password", "")


  /***
    *
    * 确定当前策略是否应为当前请求运行，比如没有填写用户名、密码
    */
  override def isValid(implicit request: HttpServletRequest) = {
    logger.info("UserPassword策略: 是否要执行（根据用户名密码是否填写）: " + (login != "" && password != "").toString())
    login != "" && password != ""
  }

  /**
    *  在真实的项目中，这里应该查询数据源（如数据库或缓存），判断密码等是否匹配
    *  为了方便用户，我们只验证用户名密码，如果成功返回这个用户的实体
   */
  def authenticate()(implicit request: HttpServletRequest, response: HttpServletResponse): Option[User] = {
    logger.info("UserPassword策略：正在尝试验证")

    if(login == "foo" && password == "foo") {
      logger.info("UserPassword策略: 登录成功")
      Some(User("foo"))
    } else {
      logger.info("UserPassword策略: 登录失败")
      None
    }
  }

  /**
   * 如果用户目前没有验证，应该发生什么？
    * 也就是说，用户未登陆，一般跳转到登陆页面
   */
  override def unauthenticated()(implicit request: HttpServletRequest, response: HttpServletResponse) {
    app.redirect("/sessions/new")
  }

}

